﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using Dapper;

namespace CodeGenerator.Core
{
    public class SqlHelper
    {

        #region 公开方法
       
        /// <summary>
        /// 单个数据集查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static List<T> Query<T>(string sql, object parms = null)
        {
            using (IDbConnection conn = GetOpenConnection())
            {
                return conn.Query<T>(sql, parms).ToList();
            }
        }

        /// <summary>
        /// 数据集查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static List<T> QueryList<T>(string sql, object parms = null)
        {
            using (IDbConnection conn = GetOpenConnection())
            {
                return conn.Query<T>(sql, parms).ToList();
            }
        }
        #endregion

        

        #region 私有方法
        private static IDbConnection GetOpenConnection()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            string providerName = ConfigurationManager.ConnectionStrings["ConnectionString"].ProviderName;
            IDbConnection connection = null;
            switch (providerName)
            {
                case "SqlServer":
                    connection = new SqlConnection(connectionString);
                    break;
                default: connection = new SqlConnection(connectionString);
                    break;
            }
            if (connection.State == ConnectionState.Closed)
                connection.Open();
            return connection;
        }


        
        #endregion
    }
}
